package com.example.springweb.service;

import com.example.springweb.mapper.UserMapper;
import com.example.springweb.pojo.User;
import com.example.springweb.utils.AccountLockedUtils;
import com.example.springweb.utils.LoginReturnMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;

import static com.example.springweb.constant.StringConstant.*;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AccountLockedUtils accountLockedUtils;


    /**
    * @deprecated  进行登录
    * @param user 保存密码和账号的实例
    * @return  com.login.utils.LoginReturnMessage 登录结果信息.成功了还是失败了
    * @Date  2021/12/22
    */
    public LoginReturnMessage TryLogin(User user){
        if(accountLockedUtils.isAccountLocked(user.getUser())){
            return new LoginReturnMessage(STRING_LOGIN_FAIL,3,accountLockedUtils.getAccountLockedTime(user));
        }

        List<User> listuser=userMapper.trylogin(user);

        if(listuser.size()>0){
            accountLockedUtils.cleanFrequencyForAccountLocked(user.getUser());
            return new LoginReturnMessage(STRING_LOGIN_SUCCESS,0, 0L);
        }

        //若帐号未被锁定,但输入密码错误,则密码错误次数+1,返回+1后的密码错误次数,次数+1后的时间(0或者1hour)
        accountLockedUtils.addFrequencyForAccountLocked(user.getUser());
        Integer errorFrequency = accountLockedUtils.getErrorFrequency(user.getUser());
        Long accountLockedTime = accountLockedUtils.getAccountLockedTime(user);
        return new LoginReturnMessage(STRING_LOGIN_FAIL,errorFrequency, accountLockedTime);

    }

    /**
        * @deprecated  注册
        * @param user 需要注册的账号和密码
        * @return  java.lang.Long 注册成功后账号的id
        * @Date  2021/12/22
        */
    public String Register(User user){
        if(DetectUserExists(user)){
            return STRING_REGISTER_FAIL_EXISTS;
        }
        Timestamp createTime=new Timestamp(System.currentTimeMillis());
        user.setCreate_time(createTime);
        user.setModify_time(createTime);
        userMapper.register(user);
//        Long id= user.getId();
        return STRING_REGISTER_SUCCESS;
    }

    /**
        * @deprecated  检测用户是否已经存在
        * @param user 想要注册用户的相关信息
        * @return  boolean true :用户已经存在  false :用户未被注册过
        * @Date  2021/12/22
        */
    public boolean DetectUserExists(User user){
        List<User> listUser= userMapper.detectuserexidts(user);
        if(listUser.size()>0)return true;
        return false;
    }


}
